#-*- coding: UTF-8 -*- 


# python3 -m pip install apachelogs
# pip3 install apachelogs

from apachelogs import LogParser
from pprint import pprint


file_name="/Users/mac/zwn/zwn_git/simple_shell_course/apache_log/zwnPython/log/m-access_log_2021-04-05"
dirFile='/Users/mac/zwn/zwn_git/simple_shell_course/apache_log/zwnPython/log/'
exitKeyId='recommenduid'
recommendUidData = {}
statusOk = '200'


# https://github.com/jwodder/apachelogs
# https://apachelogs.readthedocs.io/en/stable/directives.html

parser = LogParser("%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"")
# The above log format is also available as the constant `apachelogs.COMBINED`.
# 解析单个日志条目：
entry = parser.parse('209.126.136.4 - - [01/Nov/2017:07:28:29 +0000] "GET / HTTP/1.1" 301 521 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"\n')

# print('-ip-',entry.remote_host,entry.request_time,'-uri-',entry.request_line,entry.final_status,entry.bytes_sent,entry.headers_in['Referer'],entry.headers_in["User-Agent"])

# Log entry components can also be looked up by directive:
# print(entry.directives["%r"],entry.directives["%>s"],entry.directives["%U"],entry.directives["%{Referer}i"],entry.directives["%{User-Agent}i"])
# 现有都哪些指令能被使用
pprint(entry.directives)

"""
{'%>s': 301,
 '%b': 521,
 '%h': '209.126.136.4',
 '%l': None,
 '%r': 'GET / HTTP/1.1',
 '%t': datetime.datetime(2017, 11, 1, 7, 28, 29, tzinfo=datetime.timezone.utc),
 '%u': None,
 '%{Referer}i': None,
 '%{User-Agent}i': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                   'AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/57.0.2987.133 Safari/537.36'}
"""
# print(entry.directives["%u"])
#for list in entry:
#    pprint(entry[list])

# parse_apache_timestamp('[01/Nov/2017:07:28:29 +0000]')

parser = LogParser("%h %{HTTP_HOST}e %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %{UID}C %{SESSIONID}C")

#with open(file_name, 'r') as fp:
#  for entry in parser.parse_lines(fp):
#      print(str(entry.request_time), entry.request_line, entry.request_uri)